package com.kingyea.app.market.authorize.controller;

import com.alibaba.fastjson.JSON;
import com.kingyea.app.market.appBaseInfo.bean.AppBaseInfo;
import com.kingyea.app.market.appBaseInfo.service.AppBaseInfoService;
import com.kingyea.app.market.auth.bean.Authorize;
import com.kingyea.app.market.auth.bean.AuthorizeVo;
import com.kingyea.app.market.authorize.service.AuthorizeService;
import com.kingyea.app.market.client.OrganizationServiceClient;
import com.kingyea.app.market.client.UserServiceClient;
import com.kingyea.app.market.dept.bean.Organization;
import com.kingyea.app.market.utils.BasePage;
import com.kingyea.app.market.utils.StateCode;
import com.kingyea.app.market.utils.page.PageInfo;
import com.kingyea.mobilepolice.system.Result;
import com.kingyea.mobilepolice.user.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RequestMapping(value = "/authorize")
@RestController
public class AuthorizeController {
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private OrganizationServiceClient organizationServiceClient;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private AppBaseInfoService appBaseInfoService;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object list(@RequestBody Map<String, Object> obj) throws Exception {
        return authorizeService.list(obj);
    }

    /**
     * 授权部门
     *
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Object create(@RequestBody Map<String, Object> map) throws Exception {
        Object authObj = map.get("organization");
//		List<AuthVo> authVoObj = JSON.parseArray(JSON.toJSONString(authObj), AuthVo.class);

        Organization orgObj = JSON.parseObject(JSON.toJSONString(authObj), Organization.class);
//			if (map.size()==1) {//勾选整个部门 ，未加载全部数据
//				for (AuthVo authVo : authVoObj) {//页面勾选部门
        //获取该部门下的子部门，
//					Map<String, Object> seachMap = new HashMap();
//					seachMap.put("orgIds", authVo.getOrgSerialNo());
//					JSON.toJSONString(organizationServiceClient.tree2(seachMap));
//					Result<List<OrganizationVo>> tree = organizationServiceClient.tree(seachMap);//获取勾选的部门及该部门下的所有部门
//					List<OrganizationVo> data = tree.getData();
//					for (OrganizationVo organizationVo : data) {//遍历所有部门
        //授权部门
        Authorize authorize = new Authorize();
        String appCode = null;
        if (map.containsKey("appBaseInfo")) {
            Object appObj = map.get("appBaseInfo");//获取页面传来的appcode
            AppBaseInfo appBaseInfoObject = JSON.parseObject(JSON.toJSONString(appObj), AppBaseInfo.class);
            appCode = appBaseInfoObject.getAppCode();
        }
        if (map.containsKey("appCode")) {
            Object object = map.get("appCode");
            appCode = object.toString();
        }
        if (!StringUtils.isEmpty(orgObj.getOrgSerialNo())) {
            authorize.setDept(orgObj.getOrgSerialNo());
//							authorize.setDept(authVo.getOrgSerialNo());
        }
        authorize.setAppCode(appCode);
        authorize.setCreateDate(new Date(System.currentTimeMillis()));
        authorizeService.save(authorize);
        // 获取部门下的人
        Map<String, Object> userMap = new HashMap();
        userMap.put("orgSerialNo", orgObj.getOrgSerialNo());
        Result<BasePage<User>> list = userServiceClient.list(userMap);//根据组织唯一标志  查询用户
        System.out.println("------------------------------------------------------------------");
        System.out.println(list.toString());

        if (list.getCode().equals(StateCode.OPERATION_SUCCESS)) {
            List<User> userLists = JSON.parseArray(JSON.toJSONString(list.getData().getList()).toString(), User.class);
////							   todo  批量插入  授权人
            if (userLists.size() > 0) {
                authorizeService.doSave(appCode, userLists);
            }
        }
//					}
//				}
//			}
        return map; //authorizeService.save(authorize);
    }

    /**
     * 取消授权
     *
     * @param authorize
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    public Object delete(@RequestBody Map<String, Object> authorize) throws Exception {
//    	String id = authorize.get("accreditId").toString();
        Object organizeObj = authorize.get("organization");
        Organization orgObj = JSON.parseObject(JSON.toJSONString(organizeObj), Organization.class);
        if (authorize.containsKey("appBaseInfo")) {
            Object object = authorize.get("appBaseInfo");
            AppBaseInfo appObj = JSON.parseObject(JSON.toJSONString(object), AppBaseInfo.class);
            authorize.put("appCode", appObj.getAppCode());
        }
        authorize.put("dept", orgObj.getOrgSerialNo());
        List<Authorize> list = authorizeService.list(authorize);//部门
        if (list.size() == 1) {
            for (Authorize authorize2 : list) {

                authorizeService.deleteAuth(authorize2);
            }
//    		Authorize authorize1 = (Authorize) list;
//    		Authorize authorize1 = JSON.parseObject(JSON.toJSONString(list).toString(), Authorize.class);
//    		String valueOf = JSON.parseObject(JSON.toJSONString(list).valueOf(Authorize.class), Authorize.class);
//    		JSON.parseObject(JSON.toJSONString(list).valueOf(Authorize.class), Authorize.class);
        } else {
            System.out.println("【授权部门数据异常】");
        }
        // 用户
        authorize.put("orgSerialNo", orgObj.getOrgSerialNo());
        Result<BasePage<User>> userListResult = userServiceClient.list(authorize);// 部门下的所有用户
        if (userListResult.getCode().equals(StateCode.OPERATION_SUCCESS)) {
            List<User> userLists = JSON.parseArray(JSON.toJSONString(userListResult.getData().getList()).toString(), User.class);
            for (User user : userLists) {
                Map<String, Object> map = new HashMap();
                map.put("user", user.getUserId());
                map.put("appCode", authorize.get("appCode"));
                List<Authorize> list2 = authorizeService.list(map);//授权的用户
                for (Authorize authorize2 : list2) {
                    authorizeService.deleteAuth(authorize2);
                }
            }
        }
        return null;//authorizeService.deleteById(id);
    }

    @RequestMapping(value = "/getById", method = RequestMethod.POST)
    public Authorize detail(@PathVariable String accreditId) throws Exception {
        return authorizeService.getById(accreditId);
    }

    /**
     * 获取部门列表
     *
     * @return
     */
    @RequestMapping(value = "/deptList", method = RequestMethod.POST)
    public Object getDept(@RequestBody Map<String, Object> map) {
        map.put("pageNo", map.get("pageNum"));
        Result<BasePage<Organization>> authDept = organizationServiceClient.authDept(map);
//		JSON.parseArray(JSON.toJSONString(authDept).toString(), PageInfo.class);
//		Result<BasePage<Organization>> ationLists = JSON.parseArray(JSON.toJSONString(authDept).toString(), Organization.class);
//		return authDept;
        PageInfo<Object> pageInfo = new PageInfo<>();
        pageInfo.setList(authDept.getData().getList());
        pageInfo.setPageNum(authDept.getData().getPageNum());
        pageInfo.setPageSize(authDept.getData().getPageSize());
        pageInfo.setTotal(authDept.getData().getTotal());
        return pageInfo;


    }

    /**
     * 获取用户列表
     *
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/userList", method = RequestMethod.POST)
    public Object getUser(@RequestBody Map<String, Object> map) throws Exception {
        ArrayList<AuthorizeVo> arrayList = new ArrayList<AuthorizeVo>();
        map.put("pageNo", map.get("pageNum"));
        Result<BasePage<User>> list = userServiceClient.list(map);//根据部门获取部门下用户
        List<User> userList = JSON.parseArray(JSON.toJSONString(list.getData().getList()), User.class);
        for (User user : userList) {
            AuthorizeVo authorizeVo = new AuthorizeVo();
            authorizeVo.setUser(user);
            map.put("user", user.getUserId());
            List<Authorize> userAuthList = authorizeService.list(map);//根据应用编码，用户获取授权信息
            if (userAuthList.size() == 0) {
                authorizeVo.setIsAuth(false);
            } else if (userAuthList.size() == 1) {
                authorizeVo.setIsAuth(true);
            } else {
                authorizeVo.setIsAuth(null);
            }
            String serialNo = (String) map.get("orgSerialNo");
            Result<Organization> orgResultObj = organizationServiceClient.getBySerialNo(serialNo);
            Organization orgObj = orgResultObj.getData();
            authorizeVo.setOrganization(orgObj);
            String appCode = (String) map.get("appCode");
            AppBaseInfo appBaseInfo = appBaseInfoService.getById(appCode);
            authorizeVo.setAppBaseInfo(appBaseInfo);
            arrayList.add(authorizeVo);
        }
//		return arrayList;
        PageInfo<Object> pageInfo = new PageInfo<>();
        pageInfo.setList(arrayList);
        pageInfo.setPageNum(list.getData().getPageNum());
        pageInfo.setPageSize(list.getData().getPageSize());
        pageInfo.setTotal(list.getData().getTotal());
        return pageInfo;

    }

    /**
     * 获取应用列表
     *
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/appList", method = RequestMethod.POST)
    public Object getApp(@RequestBody Map<String, Object> map) throws Exception {
        ArrayList<AuthorizeVo> arrayList = new ArrayList<AuthorizeVo>();
        PageInfo<AppBaseInfo> appBaseListObj = (PageInfo<AppBaseInfo>) appBaseInfoService.list(map);//获取应用列表
        List<AppBaseInfo> appList = JSON.parseArray(JSON.toJSONString(appBaseListObj.getList()), AppBaseInfo.class);
//		JSON.parseObject(JSON.toJSONString(list),PageInfo<T>);
        for (AppBaseInfo appBaseInfo : appList) {
            AuthorizeVo authorizeVo = new AuthorizeVo();
//			String deptNo = map.get("deptNo").toString();
            map.put("appCode", appBaseInfo.getAppCode());
            List<Authorize> appAuthList = authorizeService.list(map);//授权应用
            if (appAuthList.size() == 0) {
                authorizeVo.setIsAuth(false);
            } else if (appAuthList.size() == 1) {
                authorizeVo.setIsAuth(true);
            } else {
                authorizeVo.setIsAuth(null);
            }
            String serialNo = (String) map.get("dept");
            Result<Organization> orgResultObj = organizationServiceClient.getBySerialNo(serialNo);
            Organization orgObj = orgResultObj.getData();
            authorizeVo.setAppBaseInfo(appBaseInfo);
            authorizeVo.setOrganization(orgObj);
            arrayList.add(authorizeVo);
        }
//		Result<Object> result = new Result<>();
//		result.setData(arrayList);
//		result
        PageInfo<Object> pageInfo = new PageInfo<>();
        pageInfo.setList(arrayList);
        pageInfo.setPageNum(appBaseListObj.getPageNum());
        pageInfo.setPageSize(appBaseListObj.getPageSize());
        pageInfo.setTotal(appBaseListObj.getTotal());
        return pageInfo;

    }

    /**
     * 用户授权
     *
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/authToUser", method = RequestMethod.POST)
    public Object authToUser(@RequestBody Map<String, Object> map) throws Exception {
        Object appObj = map.get("appBaseInfo");
        AppBaseInfo appBaseInfo = JSON.parseObject(JSON.toJSONString(appObj), AppBaseInfo.class);
        Object orgObj = map.get("organization");
        Organization organization = JSON.parseObject(JSON.toJSONString(orgObj), Organization.class);
        Object userObj = map.get("user");
        User user = JSON.parseObject(JSON.toJSONString(userObj), User.class);
        Map<String, Object> userMap = new HashMap();
        userMap.put("appCode", appBaseInfo.getAppCode());
        userMap.put("user", user.getUserId());
        List<Authorize> list = authorizeService.list(userMap);
        if (list.size() == 0) {
            Map<String, Object> deptMap = new HashMap();
            deptMap.put("appCode", appBaseInfo.getAppCode());
            deptMap.put("dept", organization.getOrgSerialNo());
            List<Authorize> deptLists = authorizeService.list(deptMap);
            if (deptLists.size() == 0) {
                //授权部门
                Authorize authorize = new Authorize();
                authorize.setAppCode(appBaseInfo.getAppCode());
                authorize.setDept(organization.getOrgSerialNo());
                authorize.setCreateDate(new Date(System.currentTimeMillis()));
                authorizeService.save(authorize);
            }
            //授权用户
            Authorize authorize = new Authorize();
            authorize.setAppCode(appBaseInfo.getAppCode());
            authorize.setUser(user.getUserId());
            authorize.setCreateDate(new Date(System.currentTimeMillis()));
            authorizeService.save(authorize);
        }
        return map;

    }

    /**
     * 取消用户授权
     *
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cancleAuthToUser", method = RequestMethod.POST)
    public Object cancleAuthToUser(@RequestBody Map<String, Object> map) throws Exception {
        Object userObj = map.get("user");
        User user = JSON.parseObject(JSON.toJSONString(userObj), User.class);
        Object appObj = map.get("appBaseInfo");
        AppBaseInfo appBaseInfo = JSON.parseObject(JSON.toJSONString(appObj), AppBaseInfo.class);
        Authorize authorize = new Authorize();
        authorize.setAppCode(appBaseInfo.getAppCode());
        authorize.setUser(user.getUserId());
        authorizeService.deleteAuth(authorize);
        return null;

    }

}
